<script lang="ts" setup>
import { ref, onMounted, h, computed } from 'vue'
import { ElMessage } from 'element-plus'
import gdjdService from '@/api/gdjd'
import { useMainStore } from '@/store/main'
import dayjs from 'dayjs'
import TreeUtilDTO from '@/utils/tree'
import treeSelect from '@/components/tree-select-edl/treeSelect.vue'
import ExportUtil from '@/utils/table-export'
import xtpzService from '@/api/xtpz'

const mainStore = useMainStore()
// 入参
const currentLevel = ref(1)
const exportParam = ref({
  url: '',
  params: {},
})
// 办结日期
const createTime = ref([new Date(new Date().getFullYear(), 0, 1), new Date()])
// 能否生成报表
const generateReportable = computed(() => mainStore.userInfo.anqxList.includes('003002b001'))
// 生命周期
onMounted(async () => {
  await queryDlrsjqx()
})

const loading = ref<boolean>(false)

/*
 * 查询承办单位
 */
const dwList = ref<any[]>([])
const bmList = ref<any[]>([])
const privateData = ref(false)

const queryDlrsjqx = async (refresh?: boolean) => {
  await xtpzService.getDlrsjqx({}).then((res: any) => {
    if (!res.data.txbmList) {
      privateData.value = true
      currentLevel.value = 3
      form.value.cbbmbm = mainStore.userInfo.bmbm
      form.value.cbdwbm = mainStore.userInfo.dwbm
      form.value.xzlx = '2'
      checkRowClick({
        cbbmbm: mainStore.userInfo.bmbm,
        cbdwbm: mainStore.userInfo.dwbm,
      })
    } else {
      dwList.value = TreeUtilDTO.getTreeData(
        (res.data.sqdwxxList || []).map((el: any) => ({
          ...el,
          mc: el.dwmc,
          dm: el.dwbm,
          fdm: el.fdwbm,
        })),
        'dwbm',
        'fdwbm',
      )
      bmList.value = res.data.txbmList || []
      if (form.value.dwbmList.length === 0) {
        const flattenList = res.data.sqdwxxList?.map((el: any) => el.dwbm)
        form.value.dwbmList.push(...flattenList)
        cbdwbmChange()
      }
      form.value.xzlx = '1'
      queryThhjTable(refresh)
    }
  })
}

/*
 * 导出excel
 */
const exportTable = (e: Event) => {
  e.preventDefault()
  // 表头
  let headerList = []
  if (thyyValue.value === '1') {
    headerList = tableData.value.titles.map((el: any) => {
      return {
        prop: el.prop,
        label: el.label2 ? el.label + '\n' + el.label2 : el.label,
      }
    })
  } else {
    headerList = tableData.value.titles1.map((el: any) => {
      return {
        prop: el.prop,
        label: el.label2 ? el.label + '\n' + el.label2 : el.label,
      }
    })
  }

  const params = {
    total: tableData.value.data.length,
    http: {
      ...exportParam.value,
      dataStructure: ['data'],
    },
    excel: {
      wjmc: '审核退回监督',
      headers: headerList,
    },
  }
  ExportUtil.allPage(params)
}

/*
 * 点击单位/部门下钻查询列表
 */
const bmInfo = ref()
const ryInfo = ref()
const checkRowClick = (row?: any) => {
  switch (currentLevel.value) {
    case 1:
      form.value.sjlx = '1'
      if (thyyValue.value === '1') {
        queryThhjTable()
        tableData.value.titles[0] = {
          label: '承办单位',
          prop: 'cbdwmc',
          width: 300,
          custom: true,
        }
      } else {
        queryThyyTable()
        tableData.value.titles1[0] = {
          label: '承办单位',
          prop: 'cbdwmc',
          width: 300,
          custom: true,
        }
      }

      break
    case 2:
      form.value.cbdwbm = row?.cbdwbm
      form.value.sjlx = '2'
      bmInfo.value = row
      if (thyyValue.value === '1') {
        queryThhjTable()
        tableData.value.titles[0] = {
          label: '承办部门',
          prop: 'cbbmmc',
          width: 300,
          custom: true,
        }
      } else {
        queryThyyTable()
        tableData.value.titles1[0] = {
          label: '承办部门',
          prop: 'cbbmmc',
          width: 300,
          custom: true,
        }
      }

      break
    case 3:
      form.value.cbbmbm = row.cbbmbm
      // form.value.cbdwbm = row.cbdwbm
      form.value.sjlx = '3'
      if (thyyValue.value === '1') {
        queryThhjTable()
        tableData.value.titles[0] = {
          label: '检察官',
          prop: 'cbjcg',
          width: 200,
        }
      } else {
        queryThyyTable()
        tableData.value.titles1[0] = {
          label: '检察官',
          prop: 'cbjcg',
          width: 200,
        }
      }
      ryInfo.value = row

      break
  }
}

/*
 * 返回上一层
 */
const preStep = (e: Event) => {
  e.preventDefault()
  currentLevel.value--
  if (currentLevel.value === 1) {
    checkRowClick()
  } else if (currentLevel.value === 2) {
    checkRowClick(bmInfo.value)
  }
}

/*
 * 生成退回环节报表
 */

const generateThhjReport = () => {
  const params = {
    cbdwbmList: dwbmList.value.map((item) => {
      return {
        dwbm: item.dwbm,
        dwmc: item.dwmc,
      }
    }),
    cbbmbmList: bmList.value.map((el) => {
      return {
        bmbm: el.bmbm,
        bmmc: el.bmmc,
      }
    }),
    bjksrq: createTime.value?.length ? dayjs(createTime.value[0]).format('YYYY-MM-DD') : '',
    bjjsrq: createTime.value?.length ? dayjs(createTime.value[1]).format('YYYY-MM-DD') : '',
  }
  gdjdService
    .createThhjjdbb(params)
    .then(() => {
      ElMessage({ type: 'success', message: '生成报表成功' })
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

/*
 * 生成退回原因报表
 */

const generateThyyReport = () => {
  const params = {
    cbdwbmList: dwbmList.value.map((item) => {
      return {
        dwbm: item.dwbm,
        dwmc: item.dwmc,
      }
    }),
    cbbmbmList: bmList.value.map((el) => {
      return {
        bmbm: el.bmbm,
        bmmc: el.bmmc,
      }
    }),
    bjksrq: createTime.value?.length ? dayjs(createTime.value[0]).format('YYYY-MM-DD') : '',
    bjjsrq: createTime.value?.length ? dayjs(createTime.value[1]).format('YYYY-MM-DD') : '',
  }
  gdjdService
    .createThyyjdbb(params)
    .then(() => {
      ElMessage({ type: 'success', message: '生成报表成功' })
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

/*
 * 查询退回环节数据列表
 */
// 查询审核退回环节监督
const form = ref<any>({
  dwbmList: [], // 单位编码
  bjksrq: '', // 办结开始日期
  bjjsrq: '', // 办结结束日期
  sjlx: '1', // 数据类型(1 单位 2. 部门 3 人员)
  cbdwbm: '',
  cbbmbm: '',
  xzlx: '1',
})

// 表格数据
const tableData = ref<any>({
  data: [],
  titles: [
    {
      label: '承办单位',
      prop: 'cbdwmc',
      width: 300,
      custom: true,
    },
    { label: '提交审核数(次)', prop: 'tjshs', width: 150 },
    { label: '审核退回数(次)', prop: 'shths', width: 150 },
    { label: '审核退回率(%)', label2: '审核退回数/提交审核数', prop: 'shthl', width: 200 },
    { label: '检察官退回数(次)', prop: 'jcgthcs', width: 200 },
    { label: '占比(%)', prop: 'jcgthzb', width: 120 },
    { label: '初验退回数(次)', prop: 'cyths', width: 200 },
    { label: '占比(%)', prop: 'cythzb', width: 120 },
    { label: '复验退回数(次)', prop: 'fyths', width: 200 },
    { label: '占比(%)', prop: 'fythzb', width: 120 },
  ],
  titles1: [
    {
      label: '承办单位',
      prop: 'cbdwmc',
      width: 300,
      custom: true,
    },
    { label: '提交审核数(次)', prop: 'tjshs', width: 150 },
    { label: '审核退回数(次)', prop: 'shths', width: 150 },
    { label: '审核退回率(%)', label2: '审核退回数/提交审核数', prop: 'shthl', width: 200 },
    { label: '案卷信息不合格(次)', prop: 'ajxxbhgs', width: 180 },
    { label: '占比(%)', prop: 'ajxxbhgzb', width: 100 },
    { label: '人员信息不合格(次)', prop: 'ryxxbhgs', width: 180 },
    { label: '占比(%)', prop: 'ryxxbhgzb', width: 100 },
    { label: '目录信息不合格(次)', prop: 'mlxxbhgs', width: 180 },
    { label: '占比(%)', prop: 'mlxxbhgzb', width: 100 },
    { label: '音像信息不合格(次)', prop: 'yxxxbhgs', width: 180 },
    { label: '占比(%)', prop: 'yxxxbhgzb', width: 100 },
    { label: '文件顺序不合格(次)', prop: 'wjpxbhgs', width: 180 },
    { label: '占比(%)', prop: 'wjpxbhgzb', width: 100 },
    { label: '文件不齐全(次)', prop: 'wjbqs', width: 150 },
    { label: '占比(%)', prop: 'wjbqzb', width: 100 },
    { label: '页号编写不规范(次)', prop: 'yhbxbgfs', width: 180 },
    { label: '占比(%)', prop: 'yhbxbgfzb', width: 100 },
    { label: '其他', prop: 'qts', width: 80 },
    { label: '占比(%)', prop: 'qtzb', width: 100 },
  ],
})

// 退回环节
const queryThhjTable = (refresh?: boolean) => {
  const params = {
    cbdwbmList: dwbmList.value.map((item) => {
      return {
        dwbm: item.dwbm,
        dwmc: item.dwmc,
      }
    }),
    bmbm: form.value.cbbmbm,
    cbdwbm: form.value.cbdwbm,
    bjksrq: createTime.value?.length ? dayjs(createTime.value[0]).format('YYYY-MM-DD') : '',
    bjjsrq: createTime.value?.length ? dayjs(createTime.value[1]).format('YYYY-MM-DD') : '',
    sjlx: form.value.sjlx,
    xzlx: form.value.xzlx,
  }
  exportParam.value = {
    url: `${window.IPCONFIG}/api/gdjd/queryGdzljdshthhj`,
    params,
  }
  loading.value = true
  gdjdService
    .queryGdzljdshthhj(params)
    .then((res) => {
      tableData.value.data = res.data
      if (refresh) ElMessage({ type: 'success', message: '刷新成功' })
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

/*
 * 查询退回原因数据列表
 */

const queryThyyTable = (refresh?: boolean) => {
  const params = {
    cbdwbmList: dwbmList.value.map((item) => {
      return {
        dwbm: item.dwbm,
        dwmc: item.dwmc,
      }
    }),
    bmbm: form.value.cbbmbm,
    cbdwbm: form.value.cbdwbm,
    bjksrq: createTime.value?.length ? dayjs(createTime.value[0]).format('YYYY-MM-DD') : '',
    bjjsrq: createTime.value?.length ? dayjs(createTime.value[1]).format('YYYY-MM-DD') : '',
    sjlx: form.value.sjlx,
    xzlx: form.value.xzlx,
  }
  exportParam.value = {
    url: `${window.IPCONFIG}/api/gdjd/queryGdzlshthyy`,
    params,
  }
  loading.value = true
  gdjdService
    .queryGdzlshthyy(params)
    .then((res) => {
      tableData.value.data = res.data
      if (refresh) ElMessage({ type: 'success', message: '刷新成功' })
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

// 刷新
const curren2Refresh = (e: Event) => {
  e.preventDefault()
  if (thyyValue.value === '1') {
    createTime.value = [new Date(new Date().getFullYear(), 0, 1), new Date()]
    queryThhjTable(true)
  } else {
    createTime.value = [new Date(new Date().getFullYear(), 0, 1), new Date()]
    queryThyyTable(true)
  }
}

const thyyValue = ref('1')

const thList = ref([
  {
    dm: '1',
    mc: '退回环节',
  },
  {
    dm: '2',
    mc: '退回原因',
  },
])

const thChange = () => {
  if (currentLevel.value === 1) {
    checkRowClick()
  } else if (currentLevel.value === 2) {
    checkRowClick(bmInfo.value)
  } else if (currentLevel.value === 3) {
    checkRowClick(ryInfo.value)
  }
}

// 刷新
const refreshClick = () => {
  if (thyyValue.value === '1') {
    queryDlrsjqx(true)
  } else {
    queryThyyTable(true)
  }
}

// 生成报表
const generateReport = () => {
  if (thyyValue.value === '1') {
    generateThhjReport()
  } else {
    generateThyyReport()
  }
}

const dwbmList = ref<any[]>([])
const cbdwbmChange = () => {
  const treeList = TreeUtilDTO.flatten(dwList.value)
  dwbmList.value = []
  treeList.forEach((item: any) => {
    form.value.dwbmList?.forEach((el: any) => {
      if (item.dwbm === el) {
        dwbmList.value.push(item)
      }
    })
  })
}

// 点击查询按钮
const querySearch = () => {
  if (thyyValue.value === '1') {
    queryDlrsjqx()
  } else {
    queryThyyTable()
  }
}

// 排序
const sortChange = (obj: any) => {
  console.log(obj, 'obj.prop')
}

// 自定义合计方法
const getSummaries = (param: { columns: any[]; data: any[] }) => {
  const { columns, data } = param
  const sums: any[] = []
  const totalData = data.pop()
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = h('div', null, ['合计'])
      return
    } else {
      if (typeof totalData[column.property] === 'number') {
        sums.push(totalData[column.property])
      } else {
        sums.push('')
      }
    }
  })
  return sums
}
</script>
<template>
  <div class="container">
    <!--表单-->
    <div class="form-box">
      <el-form :model="form" ref="filterFormRef" inline label-width="100px">
        <el-form-item
          v-if="currentLevel === 1 && !privateData"
          prop="dwbmList"
          :rules="[
            {
              required: true,
              message: '必选',
            },
          ]"
          label="承办单位:"
        >
          <tree-select
            ref="treeSelectRef"
            style="width: 300px"
            v-model="form.dwbmList"
            @update:modelValue="cbdwbmChange"
            multiple
            showAllSelection
            node-key="dwbm"
            :treeProps="{
              children: 'children',
              label: 'dwmc',
              value: 'dwbm',
            }"
            :options="dwList"
            :clearable="false"
            :check-strictly="true"
            :isLeafNode="false"
          >
          </tree-select>
        </el-form-item>
        <el-form-item v-if="currentLevel === 1 || privateData" label="办结日期:">
          <el-date-picker
            style="width: 240px"
            v-model="createTime"
            type="daterange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :clearable="false"
          />
        </el-form-item>

        <el-form-item v-if="currentLevel === 1 || privateData">
          <el-radio-group v-model="thyyValue" class="ml-4" @change="thChange">
            <el-radio
              v-for="zrritem in thList"
              :key="zrritem.dm"
              :value="zrritem.dm"
              :label="zrritem.mc"
            ></el-radio> </el-radio-group
        ></el-form-item>

        <el-form-item v-if="currentLevel === 2">
          <span class="zzjg">{{ bmInfo?.cbdwmc }}</span>
        </el-form-item>
        <el-form-item v-if="currentLevel === 3">
          <span class="zzjg">{{ ryInfo?.cbbmmc }}</span>
        </el-form-item>

        <el-form-item class="dwmcInfo">
          <el-form-item>
            <el-radio-group
              v-model="thyyValue"
              v-if="currentLevel !== 1 && !privateData"
              @change="thChange"
            >
              <el-radio
                v-for="zrritem in thList"
                :key="zrritem.dm"
                :value="zrritem.dm"
                :label="zrritem.mc"
              ></el-radio> </el-radio-group
          ></el-form-item>
          <div class="dwmcInfoButton">
            <button
              class="btn_operation"
              v-if="(currentLevel == 2 || currentLevel == 3) && !privateData"
              @click="exportTable"
            >
              <div class="btn-export"></div>
              导出EXCEL
            </button>
            <button
              class="btn_operation"
              @click="curren2Refresh"
              v-if="(currentLevel == 2 || currentLevel == 3) && !privateData"
            >
              <div class="btn-refresh"></div>
              刷新
            </button>
            <button
              class="btn_operation"
              @click="preStep"
              v-if="(currentLevel == 2 || currentLevel == 3) && !privateData"
            >
              <div class="btn-back"></div>
              返回
            </button>
          </div>
        </el-form-item>

        <el-form-item class="search" v-if="currentLevel === 1 || privateData">
          <el-button type="primary" @click="querySearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="button-group" v-if="currentLevel == 3 && privateData">
      <button class="btn_operation" @click="exportTable">
        <div class="btn-export"></div>
        导出EXCEL
      </button>
      <button class="btn_operation" @click="curren2Refresh">
        <div class="btn-refresh"></div>
        刷新
      </button>
    </div>

    <div class="button-group" v-if="currentLevel == 1">
      <button v-if="generateReportable" class="btn_operation" @click="generateReport">
        <div class="btn-export"></div>
        生成报表
      </button>
      <button class="btn_operation" @click="exportTable">
        <div class="btn-export"></div>
        导出EXCEL
      </button>
      <button class="btn_operation" @click="refreshClick">
        <div class="btn-refresh"></div>
        刷新
      </button>
    </div>

    <!-- 表格 -->
    <div class="table-box">
      <el-table
        border
        :data="tableData.data"
        stripe
        row-key="id"
        height="100%"
        v-loading="loading"
        @sort-change="sortChange"
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column label="序号" type="index" width="60"></el-table-column>
        <el-table-column
          v-for="column in thyyValue === '1' ? tableData.titles : tableData.titles1"
          :key="column.prop"
          :prop="column.prop"
          :label="column.label"
          :width="column.width"
          sortable
          resizable
        >
          <template v-if="column.label2" #header>
            <div>{{ column.label }}</div>
            <span>{{ column.label2 }}</span>
          </template>
          <template #default="{ row }">
            <div v-if="column.custom">
              <el-link
                type="primary"
                class="custom-link"
                :underline="false"
                @click="
                  () => {
                    currentLevel++
                    checkRowClick(row)
                  }
                "
                >{{ row[column.prop] }}</el-link
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;

  .form-box {
    margin-bottom: 10px;
    border-bottom: 1px solid #dae4f1;
    .zzjg {
      font-size: 20px;
      padding-right: 8px;
    }
    .el-form {
      display: flex;
      .el-form-item.dwmcInfo {
        width: 100%;
        display: flex;
        flex: 1;
        justify-content: space-between;

        :deep(.el-form-item__content) {
          display: flex;
          justify-content: flex-end;
        }
      }
      .el-form-item.search {
        margin-right: 0px;
      }
    }
  }
  .el-table--border::after {
    width: 0;
  }
  :deep(.el-table__cell) {
    border-right: 0 !important;
  }
  :deep(.el-table__border-left-patch) {
    display: none;
  }

  .button-group {
    display: flex;
    justify-content: flex-end;
    // margin-right: 32px;
    margin-bottom: 10px;
  }

  .table-box {
    flex: 1;
    height: calc(100% - 100px);
  }
}
</style>
